<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
        <div class="common-layout">
            <el-container>
                <el-main>
                    <el-row>
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple">
                                <h4>基本信息</h4>
                                <el-form :inline="true" :model="salesInvoices" :rules="rules" status-icon ref="formRef">
                                    <el-form-item label="单据编号" prop="code">
                                        <el-input
                                            v-model="salesInvoices.code"
                                            style="width: 240px"
                                            placeholder="请输入单据编号"
                                            clearable
                                            :disabled="true"
                                        />
                                    </el-form-item>
                                    <!-- 客户 -->
                                    <el-form-item label="客户" prop="customerId">
                                        <el-select
                                            v-model="salesInvoices.customerId"
                                            placeholder="请选择客户"
                                            style="width: 240px"
                                            clearable
                                            filterable
                                        >
                                            <el-option
                                                v-for="customer in customerList"
                                                :key="customer.id"
                                                :label="`${customer.code} - ${customer.name}`"
                                                :value="customer.id"
                                            />
                                        </el-select>
                                    </el-form-item>
                                    <!-- 单据日期 -->
                                    <el-form-item label="单据日期" prop="codeDate">
                                        <el-date-picker
                                            v-model="salesInvoices.codeDate"
                                            type="date"
                                            placeholder="请选择日期"
                                            value-format="YYYY-MM-DD"
                                            :disabled-date="disabledDate"
                                        />
                                    </el-form-item>
                                    <!-- 发票号 -->
                                    <el-form-item label="发票号" prop="invoiceNum">
                                        <el-input
                                            v-model="salesInvoices.invoiceNum"
                                            style="width: 240px"
                                            placeholder="请输入发票号"
                                        />
                                    </el-form-item>
                                    <el-form-item label="发票类型" prop="invoiceType">
                                        <el-select
                                            v-model="salesInvoices.invoiceType"
                                            placeholder="请选择发票类型"
                                            style="width: 240px"
                                        >
                                            <el-option
                                                v-for="type in invoiceTypes"
                                                :key="type.value"
                                                :label="type.label"
                                                :value="type.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </el-col>
                    </el-row>
                </el-main>
            </el-container>
        </div>
    </div>
    <div>
        <div class="toolbar">
            <el-button type="primary">商品信息</el-button>
            <el-button @click="addGoodsRow">继续添加</el-button>
            <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
        </div>

        <!-- 商品信息表格 -->
        <el-table :data="tableData" border style="width: 100%" class="goods-table" @selection-change="newHHandleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column label="商品编码" width="150">
                <template #header>
                    <span class="required-label">商品编码</span>
                </template>
                <template #default="scope">
                    <el-select
                        v-model="scope.row.goodsCode"
                        placeholder="请选择商品"
                        @change="handleGoodsChange(scope.row)"
                        clearable
                    >
                        <el-option
                            v-for="item in goodsList"
                            :key="item.code"
                            :label="`${item.code} - ${item.name}`"
                            :value="item.code"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="商品名称" width="180">
                <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
            </el-table-column>
            <!-- 单位（带必填标识） -->
            <el-table-column label="单位" width="80" align="center">
<!--                <template #header>-->
<!--                    <span class="required-label">单位</span>-->
<!--                </template>-->
                <template #default="scope">{{ scope.row.unit || '' }}</template>
            </el-table-column>
            <el-table-column label="仓库" width="150">
                <template #header>
                    <span class="required-label">仓库</span>
                </template>
                <template #default="scope">
                    <el-select
                        @change="storeChange(scope.row)"
                        v-model="scope.row.storeId"
                        placeholder="请选择仓库"
                        clearable
                    >
                        <el-option
                            v-for="store in storeList"
                            :key="store.id"
                            :label="`${store.code} - ${store.name}`"
                            :value="store.id"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="开票数量" width="130" align="center">
                <template #header>
                    <span class="required-label">开票数量</span>
                </template>
                <template #default="scope">
                    <el-input
                        v-model.number="scope.row.invoicingQuantity"
                        placeholder="输入数量"
                        @input="validatePrice(scope.row, 'invoicingQuantity')"
                    />
                </template>
            </el-table-column>
            <el-table-column label="开票金额" width="120" align="center">
                <template #header>
                    <span class="required-label">开票金额</span>
                </template>
                <template #default="scope">
                    <el-input
                        v-model.number="scope.row.invoicingAmount"
                        placeholder="输入金额"
                        @input="validatePrice(scope.row, 'invoicingAmount')"
                    >
                        <template #append>元</template>
                    </el-input>
                </template>
            </el-table-column>
            <el-table-column
                v-for="col in readonlyColumns"
                :key="col.prop"
                :prop="col.prop"
                :label="col.label"
                :width="col.width"
                align="center"
            />
        </el-table>
    </div>
    <div class="total-summary">
        <div class="total-label">合计</div>
        <div class="total-amount">{{ formatTotal }}</div>
    </div>
    <el-dialog
        v-model="dialogVisible"
        title="销售出库单"
        width="80%"
        top="5vh"
    >
        <div class="dialog-header">
            <el-input
                v-model="searchForm.docCode"
                placeholder="请输入单据编号"
                style="width: 240px;margin-right: 15px"
            />
            <span class="date-label">单据日期：</span>
            <el-date-picker
                v-model="searchForm.startDate"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                style="width: 160px"
            />
            <span class="date-separator">~</span>
            <el-date-picker
                v-model="searchForm.endDate"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 160px;margin-right: 15px"
            />
            <el-button type="primary" icon="Search" @click="searchSalesOuts">查询</el-button>
            <el-button icon="Refresh" @click="resetSearch">重置</el-button>
            <el-button icon="ArrowDown">展开</el-button>
        </div>
        <div class="selected-info">
            <span>已选择{{ selectedCount }}项</span>
            <el-button link type="primary" @click="clearSelection">清空</el-button>
        </div>
        <el-table
            :data="salesOutList"
            border
            height="60vh"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column prop="code" label="单据编号" width="180"/>
            <el-table-column prop="orderDate" label="单据日期" width="120"/>
            <el-table-column prop="customerName" label="客户" width="120"/>
            <el-table-column prop="deptName" label="业务部门" width="120"/>
            <el-table-column prop="businessmanName" label="业务员" width="120"/>
            <el-table-column prop="orderStatus" label="已关闭" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.orderStatus === 1 ? 'danger' : 'success'" size="small">
                        {{ scope.row.orderStatus === 1 ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>
        </el-table>
        <div class="dialog-footer">
            <div class="pagination-wrapper">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="totalItems"
                    :page-size="PopupsPageSize"
                    :current-page="PopupsPageNo"
                    @current-change="handlePageChange"
                />
            </div>
            <div class="action-buttons">
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="confirmSelection">确定</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import request from '@/util/request';
import type { SalesQuotation, SalesOrderDetail, Goods, Customer, SalesOut } from '@/types/public-xs/salesDocuments';
import { InvoiceType, type SalesInvoice } from '@/types/public-xs/salesInvoice.ts';
import type { FormInstance } from 'element-plus';
import type {Store} from "@/types/basic/store.ts";

// 基本变量
let docCode = ref('');
let sourceSheet = ref('');
let title = ref('新增销售发票');
let goodsList = ref<Goods[]>([]);
let pageNo = ref(1);
let pageSize = ref(5);
let allPage = ref(0);
let router = useRouter();

let storeList = ref<Store[]>([])
let selectStore = async () => {
    let response = await request.post('/basic/store/getAllStore')
    storeList.value = response.data.data
}
selectStore()



// 部门选项
const departments = ref([
    { value: 1, label: '销售部' },
    { value: 2, label: '技术部' },
    { value: 3, label: '财务部' },
]);

// 商品查询条件
const queryConditions = reactive({
    combine: '',
    kid: '',
});

// 表单验证规则
const rules = reactive({
    customerId: [{ required: true, message: '请选择客户', trigger: 'blur', type: 'number' }],
    code: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
    codeDate: [{ required: true, message: '请选择单据日期', trigger: 'change,blur' }],
    invoiceNum: [{ required: true, message: '请输入发票号', trigger: 'blur' }],
    invoiceType: [{ required: true, message: '请选择发票类型', trigger: 'change', type: 'number' }]
});

const disabledDate = (time: Date) => {
    return time.getTime() > Date.now();
};

// 处理顶部按钮动作
const handleAction = (action: string) => {
    switch (action) {
        case 'choose':
            if (!salesInvoices.value.customerId) {
                ElMessage.warning('请先选择客户');
                return;
            }
            dialogVisible.value = true;
            break;
        case 'save-add':
            insertSalesInvoice();
            break;
        case 'history':
            router.push('/home/fp/xsfp');
            break;
    }
};

// 获取商品数据
async function fetchData(page: number) {
    try {
        const params = new URLSearchParams();
        params.append('pageNow', page.toString());
        params.append('pageSize', pageSize.value.toString());
        params.append('combine', queryConditions.combine);
        params.append('kid', queryConditions.kid);

        let response = await request.post('/basic/good/getGoodPage', params, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        });
        goodsList.value = response.data.data.list.map((item: any) => ({
            id: item.id,
            code: item.code,
            name: item.name,
            unique: item.unique,
            tax: item.tax,
            stock: item.stock,
            kname: item.kname,
        }));
        allPage.value = response.data.data.total || 0;
    } catch (error) {
        ElMessage.error('获取商品数据失败');
        tableData.value = [];
        allPage.value = 0;
        console.error('获取数据失败:', error);
    }
}

// 顶部按钮配置
const mainActions = ref([
    { name: 'save', label: '保存', type: 'primary', icon: 'DocumentAdd' },
    { name: 'save-add', label: '保存并新增', disabled: false },
    { name: 'audit', label: '审核', hidden: false },
    { name: 'choose', label: '选择源单', hidden: false },
    { name: 'history', label: '历史单据', badge: 3 },
]);

// 定义发票类型选项
const invoiceTypes = [
    { value: 0, label: '普通' },
    { value: 1, label: '红冲' },
    { value: 2, label: '退货' }
];

// 销售发票数据
let salesInvoices = ref<SalesInvoice>({
    id: 0,
    code: docCode.value,
    codeDate: '',
    invoiceType: null,
    customerId: null,
    invoiceNum: '',
    codeState: 1,
    originalOrderNum: '',
    amount: 0,
    orderCreationTime: new Date(),
    orderCreator: '',
    orderDepartment: '',
    modifyTime: new Date(),
    modifier: '',
});

// 监听客户选择变化
watch(
    () => salesInvoices.value.customerId,
    async (newCustomerId) => {
        if (newCustomerId) {
            await selectSalesOutByCid(newCustomerId);
        } else {
            salesOutList.value = [];
            totalItems.value = 0;
        }
    }
);

// 动态加载客户
let customerList = ref<Customer[]>([]);
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectCustomerByPage', {
        pageNo: 1,
        pageSize: 10,
    });
    customerList.value = response.data.data.list;
};

// 获取销售出库单
let salesOutList = ref<SalesOut[]>([]);
let selectSalesOutByCid = async () => {
    const params = {
        pageNo: PopupsPageNo.value,
        pageSize: PopupsPageSize.value,
        cid: salesInvoices.value.customerId,
        typeId: 6,
    };
    try {
        let response = await request.post('/xs/salesInvoice/getOutStoreList', params);
        salesOutList.value = response.data.data?.list || [];
        totalItems.value = response.data.data?.total || salesOutList.value.length;
    } catch (error) {
        ElMessage.error('获取销售出库单失败');
        salesOutList.value = [];
        totalItems.value = 0;
        console.error('获取销售出库单失败:', error);
    }
};

// 生成唯一ID
const generateUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
};

// 商品表格数据
const tableData = ref([
    {
        id: generateUUID(),
        goodId: 0,
        goodsCode: '',
        goodsName: '',
        warehouseName: '',
        quantity: 0,
        invoicingQuantity: 0,
        invoicingAmount: 0,
        storeId: null,
        // historyPrice: '点击查看',
        tax: 0,
        taxIncludedPrice: 0,
        notes: '',
        unit: '',
        kname: '',
    },
]);

// 处理商品选择
const handleGoodsChange = (row: any) => {
    const selected = goodsList.value.find((item) => item.code === row.goodsCode);
    if (selected) {
        row.goodsName = selected.name;
        row.goodsId = selected.id;
        row.stock = selected.stock;
        row.unit = selected.uname;
        row.tax = selected.tax;
        row.kname = selected.kname;
        row.quantity = Math.max(1, selected.stock || 1);
        calculateTaxPrice(row);
    } else {
        row.goodsName = '';
        row.unit = '件';
        row.stock = 0;
        row.quantity = 1;
        row.tax = 13;
        row.kname = '';
        row.taxIncludedPrice = 0;
    }
};

// 处理表格选中行
const newSelectedRows = ref<any[]>([]);
const newHHandleSelectionChange = (selection: any[]) => {
    newSelectedRows.value = selection;
};

// 删除选中行
const deleteSelectedRows = async () => {
    if (newSelectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的行');
        return;
    }
    try {
        await ElMessageBox.confirm(`确定要删除选中的 ${newSelectedRows.value.length} 行吗？`, '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        const selectedIds = new Set(newSelectedRows.value.map((row) => row.id));
        tableData.value = tableData.value.filter((row) => !selectedIds.has(row.id));
        ElMessage.success('删除成功');
    } catch (error) {
        ElMessage.info('已取消删除');
    }
};

// 价格校验
const validatePrice = (row: any, field: string) => {
    if (field === 'actualPrice') {
        row.actualPrice = row.actualPrice != null ? row.actualPrice.toString().replace(/[^\d.]/g, '') : '0';
    } else if (field === 'invoicingQuantity') {
        row.invoicingQuantity = row.invoicingQuantity != null ? Math.max(0, parseInt(row.invoicingQuantity) || 0) : 0;
    } else if (field === 'invoicingAmount') {
        row.invoicingAmount = row.invoicingAmount != null ? row.invoicingAmount.toString().replace(/[^\d.]/g, '') : '0';
    }
};

// 含税价计算
const calculateTaxPrice = (row: any) => {
    if (row.actualPrice && row.tax) {
        row.taxIncludedPrice = (row.actualPrice * (1 + row.tax / 100)).toFixed(2);
    }
};

// 只读列，与 UpdateSalesInvoice.vue 保持一致
const readonlyColumns = [
    { prop: 'kname', label: '商品种类', width: 120 },
    // { prop: 'suggestedPrice', label: '建议报价', width: 120 },
    // { prop: 'taxIncludedPrice', label: '含税单价', width: 120 },
    { prop: 'tax', label: '增值税税率 (%)', width: 150 },
];

// 显示历史报价
const showHistory = (row: any) => {
    console.log('显示历史报价:', row.goodsCode);
};

// 计算总金额
const totalAmount = computed(() => {
    return tableData.value.reduce((sum, row) => {
        const quantity = Number(row.invoicingQuantity) || 0;
        const price = Number(row.invoicingAmount) || 0;
        return sum + quantity * price;
    }, 0);
});

const formatTotal = computed(() => {
    return `¥${totalAmount.value.toFixed(2)}`;
});

// 弹窗相关
let PopupsPageNo = ref(1);
let PopupsPageSize = ref(10);
const selectedCount = ref(0);
const totalItems = ref(0);
const dialogVisible = ref(false);
const currentSelected = ref<SalesOut | null>(null);
const selectedRows = ref<SalesOut[]>([]);
const searchForm = reactive({
    docCode: '',
    startDate: '',
    endDate: '',
});

// 表格选择处理
const handleSelectionChange = (selection: any) => {
    selectedRows.value = selection;
    selectedCount.value = selection.length;
    currentSelected.value = selection.length > 0 ? selection[0] : null;
};

// 清空选择
const clearSelection = () => {
    selectedRows.value = [];
    selectedCount.value = 0;
    currentSelected.value = null;
};

// 分页处理
const handlePageChange = async (newPage: number) => {
    PopupsPageNo.value = newPage;
    await searchSalesOuts();
};

// 搜索销售出库单
const searchSalesOuts = async () => {
    try {
        const params = {
            code: searchForm.docCode,
            startDate: searchForm.startDate,
            endDate: searchForm.endDate,
            pageNo: PopupsPageNo.value,
            pageSize: PopupsPageSize.value,
            typeId: 6,
            cid: salesInvoices.value.customerId,
        };
        const res = await request.post('/xs/salesInvoice/getOutStoreList', params);
        salesOutList.value = res.data.data.list || [];
        totalItems.value = res.data.data.total || 0;
    } catch (error) {
        ElMessage.error('查询销售出库单失败');
        console.error('查询失败:', error);
    }
};

// 重置搜索
const resetSearch = () => {
    searchForm.docCode = '';
    searchForm.startDate = '';
    searchForm.endDate = '';
    searchSalesOuts();
};

// 确认选择
const confirmSelection = async () => {
    if (!currentSelected.value) {
        ElMessage.warning('请先选择一个销售出库单');
        return;
    }
    const doCode = currentSelected.value.code;
    sourceSheet.value = doCode;
    salesInvoices.value.originalOrderNum = doCode;
    ElMessage.success(`已选择源单：${doCode}`);

    try {
        const detailRes = await request.post(
            `/xs/salesInvoice/selectSalesOutByCode?code=${doCode}`
        );
        if (detailRes.data.code !== '200' || !detailRes.data.data) {
            throw new Error(detailRes.data.msg || '获取销售出库明细失败');
        }

        const details = detailRes.data.data;

        const goodsIds = details
            .map((item: any) => item.goodId)
            .filter((id: number) => id > 0);

        console.log(goodsIds,"123")

        let goodsMap = new Map();
        if (goodsIds.length > 0) {
            const goodsRes = await request.post('/basic/good/getGoodList', goodsIds);
            console.log(goodsRes)
            if (goodsRes.data.code !== '200' || !goodsRes.data.data) {
                throw new Error(goodsRes.data.message || '获取商品信息失败');
            }
            goodsRes.data.data.forEach((good: Goods) => {
                goodsMap.set(good.id, good);
            });
        }



        tableData.value = details.map((item: any) => {
            console.log(item,",",item.goodId)
            const good = goodsMap.get(item.goodId) || {};
            const actualPrice = item.invoicingQuantity > 0 ? item.invoicingAmount / item.invoicingQuantity : 0;

            return {
                id: generateUUID(),
                goodId: item.goodId,
                goodsCode: good.code || '未知编码',
                goodsName: good.name || '未知商品',
                invoicingQuantity: item.invoicingQuantity,
                invoicingAmount: item.invoicingAmount,
                actualPrice: Number(actualPrice.toFixed(2)),
                unit: good.uname || '',
                tax: item.tax,
                kname: good.kname || item.kname || '-',
                storeId:item.storeId,
                warehouseName: item.warehouseName,
            };
        });
        console.log(tableData.value)

        salesInvoices.value.orderCreator = details[0].createUser || '';
        await fetchData(1);
    } catch (error: any) {
        ElMessage.error(error.message || '加载明细数据失败');
        console.error('加载明细失败:', error);
    } finally {
        dialogVisible.value = false;
    }
};

// 生成发票明细
const generateDetails = () => {
    console.log(tableData.value)
    return tableData.value.map((item) => ({
        id: 0,
        invoiceCode: salesInvoices.value.code,
        goodId: item.goodId,
        quantity: item.quantity,
        // actualPrice: item.actualPrice,
        invoicingQuantity:item.invoicingQuantity,
        invoicingAmount:item.invoicingAmount,
        tax: item.tax,
        // discountRate: 0,
        notes: '',
        createBy: salesInvoices.value.orderCreator,
        createTime: new Date(),
        updateBy: salesInvoices.value.orderCreator,
        updateTime: new Date(),
        isDelete: 0,
        warehouseId: item.storeId,
    }));
};


// 获取单据编号（仅在新增时调用）
let getDocCode = async () => {
    let response = await request.post('/xs/counter/addCode', {docType: 'XSFP'});
    docCode.value = response.data.data;
    salesInvoices.value.code = docCode.value;
};

// 添加商品行
const addGoodsRow = () => {
    tableData.value.push({
        id: generateUUID(),
        goodId: 0,
        goodsCode: '',
        goodsName: '',
        storeId: null, // 初始化 storeId
        quantity:0,
        invoicingQuantity: 0,
        invoicingAmount: 0,
        tax: 13,
        taxIncludedPrice: 0,
        notes: '',
        actualPrice: 0,
    });
};

// 定义 formRef
const formRef = ref<FormInstance>();

// 新增销售发票
const insertSalesInvoice = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.warning('请填写完整基本信息');
            return;
        }

        if (!sourceSheet.value) {
            ElMessage.warning('请先选择一个销售出库单');
            return;
        }

        if (tableData.value.length === 0) {
            ElMessage.warning('请至少添加一条商品明细');
            return;
        }

        // 添加对“开票数量”和“开票金额”的验证
        const hasInvalidGoods = tableData.value.some(item =>
            item.invoicingQuantity === undefined ||
            item.invoicingQuantity === null ||
            item.invoicingQuantity <= 0 ||
            item.invoicingAmount === undefined ||
            item.invoicingAmount === null ||
            item.invoicingAmount <= 0
        );
        if (hasInvalidGoods) {
            ElMessage.warning('请确保所有商品的开票数量和开票金额都已填写且大于0');
            return;
        }

        try {
            const details = generateDetails();
            console.log(details)
            if (details.length === 0) {
                ElMessage.warning('请至少添加一条商品明细');
                return;
            }
            salesInvoices.value.amount = totalAmount.value;
            salesInvoices.value.originalOrderNum = sourceSheet.value;
            salesInvoices.value.modifyTime = new Date();
            salesInvoices.value.modifier = salesInvoices.value.orderCreator;

            const response = await request.post('/xs/salesInvoice/insertSalesInvoice', {
                salesInvoice: salesInvoices.value,
                details,
            });
            if (response.data.code === '200') {
                ElMessage.success('新增销售发票成功');
                // 重置表单
                salesInvoices.value = {
                    id: 0,
                    code: '',
                    codeDate: '',
                    invoiceType: InvoiceType.Normal,
                    customerId: null,
                    invoiceNum: '',
                    codeState: 1,
                    originalOrderNum: '',
                    amount: 0,
                    orderCreationTime: new Date(),
                    orderCreator: '',
                    orderDepartment: '',
                    modifyTime: new Date(),
                    modifier: '',
                };
                tableData.value = [{
                    id: generateUUID(),
                    goodId: 0,
                    goodsCode: '',
                    goodsName: '',
                    quantity: 1,
                    actualPrice: 0,
                    historyPrice: '',
                    tax: 13,
                    taxIncludedPrice: 0,
                    stock: 0,
                    unit: '',
                    kname: '',
                    warehouse: '',
                }];
                sourceSheet.value = '';
                await getDocCode();
                formRef.value.resetFields();
                await router.push('/home/fp/xsfp');
            } else {
                ElMessage.error('新增销售发票失败');
            }
        } catch (error) {
            ElMessage.error('新增销售发票失败');
            console.error('新增失败:', error);
        }
    });
};

const storeChange = async (row: any) => {
    console.log(row)
    let response = await request({
        url: '/kc/StoreGoodSummary/selectKcStoreGoodBySidCid',
        method: 'get',
        params: {
            sid: row.storeId,
            gid: row.goodId
        }
    })
    console.log(response)
    if (response.data.data) {
        row.stock = response.data.data.stock
        row.singleCost = response.data.data.singleCost
    } else {
        row.stock = 0
        row.singleCost = 0
    }
    // changeNum(row)
}

// 初始化
onMounted(async () => {
    await getDocCode();
    await selectCustomer();
    await fetchData(1);
});
</script>

<style scoped>
.el-row {
    margin-bottom: 20px;
}
.el-row:last-child {
    margin-bottom: 0;
}
.el-col {
    border-radius: 4px;
}
.grid-content {
    border-radius: 4px;
    min-height: 36px;
}
.required-label::after {
    content: "*";
    color: #f56c6c;
    margin-left: 4px;
}
.goods-table {
    margin-top: 20px;
}
.toolbar {
    margin-bottom: 15px;
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
}
.el-table :deep(.el-input__inner) {
    text-align: center;
}
.total-summary {
    background: #fff8dc;
    padding: 12px 20px;
    display: flex;
    justify-content: flex-end;
    border: 1px solid #ebeef5;
    border-top: none;
}
.total-label {
    font-weight: 600;
    color: #606266;
    margin-right: 30px;
}
.total-amount {
    color: #f56c6c;
    min-width: 120px;
    text-align: right;
    font-family: Arial, sans-serif;
}
.pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}
.dialog-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    flex-wrap: wrap;
    gap: 10px;
}
.date-label {
    color: #606266;
    margin: 0 10px;
}
.date-separator {
    margin: 0 8px;
    color: #c0c4cc;
}
.selected-info {
    margin: 12px 0;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #606266;
}
.dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 15px;
}
.pagination-info {
    color: #606266;
}
.action-buttons {
    display: flex;
    gap: 15px;
}
:deep(.el-dialog__header) {
    border-bottom: 1px solid #ebeef5;
}
</style>
